package com.ruoyi.system.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.system.domain.DataAndPage;
import com.ruoyi.system.domain.SysPythonEntity;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

public class UrlUtil {

    public static String getResponseFromApi(String url) {
        // 在这里实现发送GET请求的逻辑，并返回响应文本。可以使用Spring Web模块或其他HTTP客户端库来实现。
        // 示例代码可以使用Spring Web的RestTemplate或HttpClient来发送请求。
        // 以下是一个简单的示例，使用RestTemplate发送GET请求：
        RestTemplate restTemplate = new RestTemplate();
        try {
            String response = restTemplate.getForObject(url, String.class);
            return response;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    public static String crawlRecommendationRooms(String url) {
        RestTemplate restTemplate = new RestTemplate();

        // 创建并设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        headers.add(HttpHeaders.USER_AGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36");

        // 构建请求体
        HttpEntity<String> entity = new HttpEntity<>("body", headers);

        // 发送 GET 请求并获取响应结果
        ResponseEntity<String> response = restTemplate.exchange(
                url,
                HttpMethod.GET,
                entity,
                String.class
        );


        return response.getBody();
    }

    /**
     * 爬虫获取bilibili查询信息
     * @param url api接口
     * @param userAgent 请求头
     * @param referer
     * @param cookie cookie
     * @param origin
     * @return
     */
    public static DataAndPage crawlRecommendationRoomsSelect(String url,String userAgent,String referer,String cookie,String origin) {
        RestTemplate restTemplate = new RestTemplate();

        // 创建并设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        headers.add(HttpHeaders.USER_AGENT, userAgent);
        headers.add(HttpHeaders.REFERER,referer);
        headers.add(HttpHeaders.COOKIE,cookie);
        headers.add(HttpHeaders.ORIGIN,origin);
        // 构建请求体
        HttpEntity<String> entity = new HttpEntity<>("body", headers);
        // 发送 GET 请求并获取响应结果
        ResponseEntity<String> response = restTemplate.exchange(
                url,
                HttpMethod.GET,
                entity,
                String.class
        );
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, Object> dataMap = null;
        try {
            dataMap = objectMapper.readValue(response.getBody(), Map.class);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        DataAndPage dataAndPage = new DataAndPage();
        Map<String, List<Map<String,Object>>> dataList = (Map<String, List<Map<String,Object>>>) dataMap.get("data");
        if (dataList==null||dataList.get("result")==null){
            return dataAndPage;
        }
        List<Map<String,Object>> listdata =dataList.get("result");
        dataAndPage.setPage(dataMap);
        dataAndPage.setData(listdata);
        return dataAndPage;

    }
    /**
     * 爬虫获取bilibili视频信息
     * @param url
     * @return
     */
    public static DataAndPage crawlRecommendationRoomses(String url) {
        RestTemplate restTemplate = new RestTemplate();

        // 创建并设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);

        headers.add(HttpHeaders.USER_AGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36");

        // 构建请求体
        HttpEntity<String> entity = new HttpEntity<>("body", headers);

        // 发送 GET 请求并获取响应结果
        ResponseEntity<String> response = restTemplate.exchange(
                url,
                HttpMethod.GET,
                entity,
                String.class
        );
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, Object> dataMap = null;
        try {
            dataMap = objectMapper.readValue(response.getBody(), Map.class);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

        Map<String, List<Map<String,Object>>> dataList = (Map<String, List<Map<String,Object>>>) dataMap.get("data");
        if (dataList == null){
            return null;
        }
        List<Map<String,Object>> listdata =dataList.get("archives");
        Map<String, Object> listPage = (Map<String, Object>) dataList.get("page");
        DataAndPage dataAndPage = new DataAndPage();
        dataAndPage.setData(listdata);
        dataAndPage.setPage(listPage);
        return dataAndPage;
    }
    public static void main(String[] args) {
        String userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36";
        String referer = "https://www.bilibili.com/";
        String cookie = "buvid3=2D33388A-5D6E-5A8D-7DC1-5D22DECADDBD08777infoc; b_nut=1704785208; i-wanna-go-back=-1; b_ut=7; _uuid=F2337EFE-8C75-6198-8EF2-6DB106D4CFAC1008976infoc; enable_web_push=DISABLE; buvid4=BE566E1F-6506-6E55-2D15-1039B21AA38309416-024010907-FAtygRuAneLBGTBggB8xRg%3D%3D; header_theme_version=CLOSE; CURRENT_BLACKGAP=0; rpdid=|(umkY)RRY|k0J'u~|R)YmYk~; LIVE_BUVID=AUTO8417053930528770; is-2022-channel=1; CURRENT_FNVAL=16; PVID=1; fingerprint=50e549ed6e2770175346605c227d0a25; buvid_fp_plain=undefined; buvid_fp=50e549ed6e2770175346605c227d0a25; b_lsid=BCF8C192_18D34CB052F; home_feed_column=4; browser_resolution=904-586; bsource=search_baidu; bili_ticket=eyJhbGciOiJIUzI1NiIsImtpZCI6InMwMyIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3MDYyNDgxMTMsImlhdCI6MTcwNTk4ODg1MywicGx0IjotMX0.GItGjSgQlrNs6-viTvwg0YKenxkc7aZ8ypllYGgLXec; bili_ticket_expires=1706248053; sid=egoafji1";
        String origin = "https://www.bilibili.com";
        List<Map<String,Object>> listdata = crawlRecommendationRoomsSelect("https://api.bilibili.com/x/web-interface/search/type?search_type=video&&keyword=王老菊",userAgent,referer,cookie,origin).getData();
        https://api.bilibili.com/x/web-interface/dynamic/region?ps=15&rid=195


        listdata.forEach(data -> {
//            System.out.println(data);
//            System.out.println("--------------------------------");
            SysPythonEntity entityData = new SysPythonEntity();
            entityData.setId(1);
            entityData.setTitle(data.get("title").toString());
            entityData.setAddress("1");
            entityData.setTName(((Map<Object, Object>)data.get("owner")).get("name").toString());
            entityData.setUrl(data.get("short_link_v2").toString());
            entityData.setValue(data.get("desc").toString());
            entityData.setSubject(data.get("tname").toString());
            entityData.setNum((Integer) ((Map<Object, Object>)data.get("stat")).get("vv"));
            entityData.setDuration((Integer) ((Map<Object, Object>)data.get("stat")).get("vt"));
            entityData.setCreatTime(LocalDateTime.now());
            entityData.setUpdateTime(LocalDateTime.now());
            System.out.println(entityData.toString());

//            iSysPythonMapper.insert(entityData);
        });
    }
}
